package com.ruoyi.app.controller.front;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ruoyi.app.config.AppConfig;
import com.ruoyi.app.domain.AppCostCategoryRates;
import com.ruoyi.app.domain.AppCostCompany;
import com.ruoyi.app.domain.AppCostProject;
import com.ruoyi.app.service.IAppCostCategoryRatesService;
import com.ruoyi.app.service.IAppCostCompanyService;
import com.ruoyi.app.service.IAppCostProjectService;
import com.ruoyi.app.util.CompanyUtils;
import com.ruoyi.common.core.utils.FileUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/f")
public class AppFrontController {

    @Autowired
    private IAppCostProjectService appCostProjectService;

    @Autowired
    private IAppCostCategoryRatesService appCostCategoryRatesService;

    @Autowired
    private IAppCostCompanyService appCostCompanyService;

    /**
     * 接口测试
     * http://localhost/dev-api/app/f/index
     * @return
     */
    @GetMapping(value = "index")
    public AjaxResult index() {
        return AjaxResult.success("OK");
    }

    /**
     * 获取用户信息
     * @return
     */
    @PostMapping(value = "getUserInfo")
    public AjaxResult getUserInfo() {
        Long userId = SecurityUtils.getLoginUser().getUserId();
        Map user = appCostCompanyService.getUserInfo(userId);
        user.put("role", user.get("role").toString().split(";"));
        return AjaxResult.success("OK", user);
    }

    /**
     * 地图采集上报
     * http://localhost/dev-api/app/f/index
     * @param title 公司名称
     * @param companyPic  门头照
     * @param lat   经度
     * @param lng   维度
     * @return
     */
    @PostMapping(value = "addCompany")
    public AjaxResult addCompany(@RequestParam(value="title",defaultValue="")String title,
                         @RequestParam(value="companyPic",defaultValue="")String companyPic,
                         @RequestParam(value="lat",defaultValue="")Double lat,
                         @RequestParam(value="lng",defaultValue="")Double lng) {
        if(StringUtils.isEmpty(title)){
            return AjaxResult.error("请输入公司名称");
        }else if(StringUtils.isEmpty(companyPic)){
            return AjaxResult.error("请上传门头照");
        }else if(!(lat != null && lat > 0 && lng != null && lng > 0)){
            return AjaxResult.error("定位失败，请打开GPS");
        }else {
            AppCostCompany company = new AppCostCompany();
            company.setTitle(title);
            company.setCompanyPic(companyPic);
            company.setLat(lat);
            company.setLng(lng);
            company.setState("1");
            company.setHide(0);
            company.setDelFlag(0);
            company.setDeptId(0L);
            company.setCostType("0");
            company.setCreateId(SecurityUtils.getLoginUser().getUserId());
            company.setCreateBy(SecurityUtils.getLoginUser().getUsername());
            appCostCompanyService.insertAppCostCompany(company);
            return AjaxResult.success("添加成功，请返回", company.getId());
        }
    }

    /**
     * 更新店铺经纬度
     * @param id
     * @param lat
     * @param lng
     * @return
     */
    @PostMapping(value = "modifyLatLng")
    public AjaxResult modifyLatLng(@RequestParam(value="id",defaultValue="")Long id,
                         @RequestParam(value="title",defaultValue="")String title,
                         @RequestParam(value="companyPic",defaultValue="")String companyPic,
                         @RequestParam(value="lat",defaultValue="")Double lat,
                         @RequestParam(value="lng",defaultValue="")Double lng) {
        if(id == null){
            return AjaxResult.error("参数异常， ID不能为空");
        }else {
            AppCostCompany company = appCostCompanyService.selectAppCostCompanyById(id);
            if(lat != null && lat > 0 && lng != null && lng > 0){
                company.setLat(lat);
                company.setLng(lng);
            }
            if(StringUtils.isNotEmpty(title)){
                company.setTitle(title);
            }
            if(StringUtils.isNotEmpty(companyPic)){
                company.setCompanyPic(companyPic);
            }
            appCostCompanyService.updateAppCostCompany(company);
            return AjaxResult.success("更新经纬度成功");
        }
    }

    @PostMapping(value = "delCompany")
    public AjaxResult delCompany(@RequestParam(value="id",defaultValue="")Long id) {
        if(id == null){
            return AjaxResult.error("参数异常， ID不能为空");
        }else {
            appCostCompanyService.deleteAppCostCompanyById(id);
            return AjaxResult.success("更新经纬度成功");
        }
    }

    /**
     * 加载所有店铺经纬度
     * http://localhost/dev-api/app/f/queryLatLngList
     * @return
     */
    @PostMapping(value = "queryLatLngList")
    public AjaxResult queryLatLngList(@RequestParam(value="lat",defaultValue="")Double lat,
                                      @RequestParam(value="lng",defaultValue="")Double lng) {
        if(!(lat != null && lat > 0 && lng != null && lng > 0)){
            return AjaxResult.error("定位失败，请打开GPS");
        }else {
            List<AppCostProject> projectList = appCostProjectService.selectAppCostProjectList(new AppCostProject());
            Map<String, String> color = Maps.newConcurrentMap();
            for (AppCostProject project : projectList) {
                color.put(project.getId().toString(), AppConfig.getFilepath() + project.getColor());
            }

            String distance = appCostCompanyService.getConfigValue("app.distance");
            List<Map> list =  appCostCompanyService.queryLatLngList(lat, lng, Integer.parseInt(distance));
            for (Map map : list) {
                map.put("companyPic",  AppConfig.getFilepath() + map.get("companyPic"));
                if(map.get("state").toString().equals("2") && map.containsKey("projectId")){
                    map.put("color", color.get(map.get("projectId").toString()));
                }else{
                    map.put("color", "");
                }
            }
            return AjaxResult.success("OK", list);
        }
    }

    /**
     * 根据标题搜索
     * @param lat
     * @param lng
     * @return
     */
    @PostMapping(value = "querySearchList")
    public AjaxResult querySearchList(@RequestParam(value="title",defaultValue="")String title) {
        List<Map> list =  appCostCompanyService.querySearchList(SecurityUtils.getLoginUser().getUserId(), title);
        for (Map map : list) {
            map.put("companyPic",  AppConfig.getFilepath() + map.get("companyPic"));
        }
        return AjaxResult.success("OK", list);
    }

    /**
     * 查询店铺信息
     * http://localhost/dev-api/app/f/getCompany?id=
     * @return
     */
    @PostMapping(value = "getCompany")
    public AjaxResult getCompany(@RequestParam(value="id",defaultValue="")Long id) {
        if(id != null && id > 0){
            AppCostCompany company = appCostCompanyService.selectAppCostCompanyById(id);
            if(company != null){
                company.setCompanyPic(AppConfig.getFilepath() + company.getCompanyPic());
                if(StringUtils.isNotEmpty(company.getLicensePic())){
                    company.setLicensePic(AppConfig.getFilepath() + company.getLicensePic());
                }
                return AjaxResult.success("OK", company);
            }else{
                return AjaxResult.error("参数错误");
            }
        }else {
            return AjaxResult.error("参数错误");
        }
    }

    /**
     *  上传图片
     * http://localhost/dev-api/app/f/upload
     * 图片静态访问路径：http://localhost/dev-api/app/files/userfiles/2020/07/09/5f8204989e555f96b8689c30b1a9385d.png
     * @param picfile
     * @return
     */
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("picfile") MultipartFile picfile){
        try {

            if (!picfile.isEmpty()){
                if(picfile != null && picfile.getOriginalFilename().length()>4){
                    String picFilePath = AppConfig.getProfile();
                    String filename  = FileUtils.extractFilename("upload", picfile);
                    File file = new File(picFilePath+filename);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }
                    System.out.println("保存文件:"+picFilePath+filename);
                    try {
                        picfile.transferTo(file);
                        return AjaxResult.success("上传成功",filename);
                    } catch (Exception e) {
                        System.out.println("上传文件失败:"+picFilePath+filename);
                        e.printStackTrace();
                    }
                }
            }
            return AjaxResult.error("上传失败，请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请联系管理员");
        }
    }

    /**
     * 上传营业执照
     * @param picfile
     * @return
     */
    @PostMapping("/uploadLicense")
    public AjaxResult uploadLicense(@RequestParam("picfile") MultipartFile picfile){
        try {

            if (!picfile.isEmpty()){
                if(picfile != null && picfile.getOriginalFilename().length()>4){
                    String picFilePath = AppConfig.getProfile();
                    String filename  = FileUtils.extractFilename("license", picfile);
                    File file = new File(picFilePath+filename);
                    if (!file.getParentFile().exists()) {
                        file.getParentFile().mkdirs();
                    }

                    System.out.println("保存文件:"+picFilePath+filename);
                    try {
                        picfile.transferTo(file);
                        return AjaxResult.success("上传成功",filename);
                    } catch (Exception e) {
                        System.out.println("上传文件失败:"+picFilePath+filename);
                        e.printStackTrace();
                    }
                }
            }
            return AjaxResult.error("上传失败，请联系管理员");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请联系管理员");
        }
    }


    /***********************************************完善信息*****************************************************/
    /**
     * 查询收费标准
     * http://localhost/dev-api/app/f/queryCostProjectList
     * @return
     */
    @GetMapping(value = "queryCostProjectList")
    public AjaxResult queryCostProjectList() {
        List<AppCostProject> companyTypeList = appCostProjectService.queryCompanyTypeList();
        List<AppCostProject> projectList = appCostProjectService.selectAppCostProjectList(new AppCostProject());
        List<AppCostCategoryRates> rateList = appCostCategoryRatesService.selectAppCostCategoryRatesList(new AppCostCategoryRates());

        Map<String , List<AppCostCategoryRates>> rateMap = Maps.newConcurrentMap();
        for (AppCostCategoryRates rate : rateList) {
            if(rateMap.containsKey(rate.getCid().toString())){
                rateMap.get(rate.getCid().toString()).add(rate);
            }else{
                List<AppCostCategoryRates> list = Lists.newArrayList();
                list.add(rate);
                rateMap.put(rate.getCid().toString(), list);
            }
        }

        Map<String , List<Map>> projectMap = Maps.newConcurrentMap();
        for (AppCostProject project : projectList) {
            if(projectMap.containsKey(project.getCompanyType())){
                Map item = Maps.newConcurrentMap();
                item.put("id", project.getId());
                item.put("name", project.getName());
                item.put("children", rateMap.get(project.getId().toString()));
                projectMap.get(project.getCompanyType()).add(item);
            }else{
                List<Map> list = Lists.newArrayList();
                Map item = Maps.newConcurrentMap();
                item.put("id", project.getId());
                item.put("name", project.getName());
                item.put("children", rateMap.get(project.getId().toString()));
                list.add(item);
                projectMap.put(project.getCompanyType(), list);
            }
        }

        List<Map> dataList = Lists.newArrayList();
        for (AppCostProject companyType : companyTypeList) {
            Map item = Maps.newConcurrentMap();
            item.put("id", companyType.getId().toString());
            item.put("name", companyType.getName());
            item.put("children", projectMap.get(companyType.getId().toString()));
            dataList.add(item);
        }
        return AjaxResult.success("OK", dataList);
    }

    @PostMapping("/scanQrcode")
    public AjaxResult scanQrcode(@RequestParam("path") String path){
        try {
            Map<String, String> company = CompanyUtils.getCompanyInfo(path);
            if(company.containsKey("name") && company.containsKey("businessCode")){
                return AjaxResult.success("OK", company);
            }else{
                return AjaxResult.error("未查到主体信息，请手动填写");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请联系管理员");
        }
    }

    @PostMapping("/modifyCompnay")
    public AjaxResult modifyCompnay(AppCostCompany company){
        try {
            appCostCompanyService.updateAppCostCompany(company);
            return AjaxResult.success("OK");
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("上传失败，请联系管理员");
        }
    }
    /***********************************************完善信息*****************************************************/

}
